package cn.sintang.core.regex;

import com.google.common.collect.Maps;
import org.apache.commons.lang3.StringUtils;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 特殊字符转换工具类
 * @author sintang
 * @date 2018-01-12
 */
public class SpecialCharsetUtil {
    /**
     * 特殊字符的Map
     */
    private static final Map<String,String> charsetMap;
    static {
        charsetMap = Maps.newHashMap();
        charsetMap.put("＜","<");
        charsetMap.put("＞",">");
        charsetMap.put("＇","'");
        charsetMap.put("＂","\"");
        charsetMap.put("；",";");
    }

    /**
     * 转换特殊字符
     * @param sourceStr
     * @return
     */
    public static String convert(String sourceStr){
        // 把Map中的key值转换为以|分割的字符串
        String specialCharStr = StringUtils.join(charsetMap.keySet(), "|");
        Pattern pattern = Pattern.compile("("+specialCharStr+")");
        StringBuffer sb = new StringBuffer();
        Matcher matcher = pattern.matcher(sourceStr);
        // 批量匹配到的数据
        while(matcher.find()){
            matcher.appendReplacement(sb,charsetMap.get(matcher.group()));
        }
        matcher.appendTail(sb);
        return sb.toString();
    }

}
